// 封装一个事件上报工具类
import 'dart:convert';

import 'package:adjust_sdk/adjust.dart';
import 'package:adjust_sdk/adjust_ad_revenue.dart';
import 'package:adjust_sdk/adjust_event.dart';
import 'package:business_plugin/business/adjust_attribution_service.dart';
import 'package:business_plugin/business/config_business/config_business.dart';
import 'package:business_plugin/business/firebase_helper.dart';
import 'package:business_plugin/business/firebase_remote_config_service.dart';
import 'package:business_plugin/business/td_analytics_service.dart';
import 'package:business_plugin/utils/business_tools.dart';
import 'package:thinking_analytics/td_analytics.dart';

class ReportUtils {
  // 记录事件
  static Future<void> logEvent(String eventName, {Map<String, dynamic>? properties, String? token}) async {
    Map<String, dynamic> newProperties = {};
    if (properties != null) {
      newProperties.addAll(properties);
    }
    if (ConfigBusiness.config.reportExtraParameters != null) {
      // 合并额外参数
      newProperties.addAll(ConfigBusiness.config.reportExtraParameters!);
    }
    //删除properties中值为null的键值对
    newProperties.removeWhere((key, value) => value == null);
    // 删除properties中值为""的键值对
    newProperties.removeWhere((key, value) => value == "");
    // 转换为Firebase需要的类型
    Map<String, Object>? firebaseParams;
    if (newProperties.isNotEmpty) {
      firebaseParams = Map<String, Object>.from(newProperties);
    }
    if (FirebaseHelper.isInitialized) {
      // Firebase 上报
      FirebaseHelper.analytics.logEvent(name: eventName, parameters: firebaseParams);
      BusinessTools.log("Firebase事件上报: $eventName - $newProperties");
    }
    if (TDAnalyticsService.isInitialized) {
      // 上报到数数
      TDAnalytics.track(eventName, properties: newProperties);
    }
    if (AdjustAttributionService.isInitialized) {
      // Adjust 上报 - 需要事件映射
      _reportToAdjust(eventName: eventName, newToken: token);
    }

    BusinessTools.log("事件上报: $eventName - $newProperties");
  }

  // 只上报数数
  static void tdAnalyticsUserSet(Map<String, dynamic> properties, {String? appId}) {
    if (!TDAnalyticsService.isInitialized) {
      return;
    }
    TDAnalytics.userSet(properties, appId: appId ?? ConfigBusiness.config.tdAppId);
    BusinessTools.log("数数用户属性设置: $properties");
  }

  // 只上报数数
  static void tdAnalyticsUserSetOnce(Map<String, dynamic> properties, {String? appId}) {
    if (!TDAnalyticsService.isInitialized) {
      return;
    }
    TDAnalytics.userSetOnce(properties, appId: appId ?? ConfigBusiness.config.tdAppId);
    BusinessTools.log("数数用户属性设置(仅一次): $properties");
  }

  // Adjust 事件映射和上报
  static void _reportToAdjust({required String eventName, String? newToken}) {
    if (!FirebaseHelper.isInitialized) {
      return;
    }
    String? token = newToken;
    if (token == null) {
      //从远程配置获取事件映射的token
      Map<String, dynamic> eventTokens =
          jsonDecode(FirebaseRemoteConfigService.to.getString("ADJUST_EVENT_MAP", defaultValue: '{}'));
      // 检查是否有对应的事件令牌
      token = eventTokens[eventName];
      if (token == null) {
        //将事件名称转换为小写
        String lowerCaseEventName = eventName.toLowerCase();
        token = eventTokens[lowerCaseEventName];
        if (token == null) {
          return; // 没有对应的令牌，不上报
        }
      }
    }

    if (token.isEmpty) {
      return; // token 为空，不上报
    }

    // 创建 Adjust 事件对象
    final adjustEvent = AdjustEvent(token);

    // 发送事件
    Adjust.trackEvent(adjustEvent);
  }

  //收益上报
  // 广告收益上报到 Adjust
  static void reportToAdjust(
      {required double revenue, // 收益金额
      required String currencyCode, // 货币代码
      required String adNetwork, // 广告网络
      required String adUnit, // 广告单元
      String? adPlacement, // 广告位置
      String source = 'admob_sdk' // 接入哪个平台就写哪个参数
      }) {
    try {
      // 创建 Adjust 广告收益对象，指定来源
      final adjustAdRevenue = AdjustAdRevenue(source);

      // 设置收益金额（以美元为单位）
      adjustAdRevenue.setRevenue(revenue, currencyCode);

      // 设置广告网络信息
      adjustAdRevenue.adRevenueNetwork = adNetwork;

      // 设置广告单元
      adjustAdRevenue.adRevenueUnit = adUnit;

      // 设置广告位置（如果提供）
      if (adPlacement != null && adPlacement.isNotEmpty) {
        adjustAdRevenue.adRevenuePlacement = adPlacement;
      }

      // 发送广告收益事件
      Adjust.trackAdRevenue(adjustAdRevenue);

      // 记录日志
      BusinessTools.log("Adjust 收益上报: $revenue USD, 网络: $adNetwork, 单元: $adUnit, 位置: $adPlacement");
    } catch (e) {
      BusinessTools.log("Adjust 收益上报失败: $e");
    }
  }

  // 广告收益上报到 Firebase
  /*
  广告格式
  Banner
  Native
  Splash
  Interstitial
  Rewarded
  */
  static void reportToFirebase(
      {required String adPlatform, // 广告平台 (如 'AdMob', 'AppLovin')
      required String adSource, // 广告来源
      required String adUnitName, // 广告单元名称
      required String adFormat, // 广告格式 (如 'banner', 'interstitial', 'rewarded')
      required double value, // 收益金额
      required String currency // 货币单位，默认为美元
      }) {
    try {
      // 构建参数映射
      final Map<String, Object> params = {
        'ad_platform': adPlatform,
        'ad_source': adSource,
        'ad_unit_name': adUnitName,
        'ad_format': adFormat,
        'value': value,
        'currency': currency,
      };

      // // 发送到 Firebase Analytics
      // FirebaseHelper.analytics.logEvent(
      //   name: 'ad_impression', // 事件名称
      //   parameters: params,
      // );
      ReportUtils.logEvent(
        'ad_impression',
        properties: params,
      );

      // 记录日志
      BusinessTools.log(
          "Firebase 收益上报: $value $currency, 平台: $adPlatform, 来源: $adSource, 单元: $adUnitName, 格式: $adFormat");
    } catch (e) {
      BusinessTools.log("Firebase 收益上报失败: $e");
    }
  }
}
